var util = require('../../utils/util.js');
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    screen_h: 0,
    screen_w: 0,
    msg_img_w: 0,
    msg_img_h: 0,
    coinItem_w: 0,
    coinItem_h: 0,
    selItemIndex: 1,
    jin_e: 10,
    czRecord: [],
    coinInfoArr: '',

    showVideo: false,
    duihuanDatas: [],
    showQuan: false,
    quanImageUrl: '',
    selected: 1,

    kefuInfo: "",
    canUsePayButton: false
  },

  cuid: 0,
  token: '',
  openid: '',
  uname: '',
  hasScore: 0,//拥有的积分

  total_fee: 8,
  msg_count: 88,

  buyRecords: '',
  duihuanRecords: '',

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("chongzhi：", options)

    var that = this

    var usePayButton = false
    // 判断是否支持行业sdk 的 pay-button 组件
    if (tt.canIUse("microapp-trade-plugin")) {
      usePayButton = true
    } else {
      console.log("not nse pay-button")
    }

    app.getWxCheck(function(show) {
      that.setData({
        showVideo: show,
        canUsePayButton: usePayButton
      })
    })

    this.getLoginUserInfo()
    
    var that = this
    app.getAllAbout("contact", function (response) {
      console.log("充值信息：", response)
      that.buildDefaultCoinInfo()
      if(response && response.length > 0){
        try {
          let coinJson = JSON.parse(response)
          console.log("coinJson : ", coinJson)
          let jsonIsOk = true
          for (let i = 0; i < coinJson.length; i++) {
            let jsonData = coinJson[i]
            if (!jsonData.jin_e || jsonData.jin_e <= 0 || !jsonData.msgCount || jsonData.msgCount <= 0) {
              jsonIsOk = false
              break
            }
          }
          if (jsonIsOk) {
            that.setData({
              coinInfoArr: coinJson
            })
            that.total_fee = coinJson[1].jin_e
            that.msg_count = coinJson[1].msgCount
          } else {
            console.log("充值json数据不全")
            that.buildDefaultCoinInfo()  
          }
        } catch (error) {
          console.log("充值数据json格式有误")
          that.buildDefaultCoinInfo()
        }
      } else {
        that.buildDefaultCoinInfo()
      }
    })

    this.getCanDuihuan()

    app.getUserInfo(util.orgid, function (res) {
      console.log("小程序信息：", res)
      that.setData({
        kefuInfo: "客服热线：" + res.phone + " 9:00-12:00 14:00-18:00"
      })
    })
  },

  onShow: function () {
    var that = this
    app.initScreenInfo(function (res) {
      if (res) {
        let item_w = (app.screen_w - 50) / 3
        let item_h = item_w * 2 / 3
        that.setData({
          isIphone_x: app.isIphone_x,
          screen_w: app.screen_w,
          screen_h: app.screen_h,
          coinItem_w: item_w,
          coinItem_h: item_h,
          msg_img_w: app.screen_w,
          msg_img_h: (app.screen_w - 30) * 0.378,
        });
      }
    })
  },


  buildDefaultCoinInfo: function() {
    var defaultData = []
    for (let i = 0; i < 3; i++) {
      let data = {}
      if (i == 0) {
        data.jin_e = 8
        data.msgCount = 88
      } else if (i == 1) {
        data.jin_e = 10
        data.msgCount = 128
        this.total_fee = 10
        this.msg_count = 128
      } else {
        data.jin_e = 15
        data.msgCount = 200
      }
      defaultData.push(data)
    }
    
    this.setData({
      coinInfoArr: defaultData
    })
  },

  coinItemClick: function (e) {
    console.log("sel:", e.currentTarget.dataset)
    let index = parseInt(e.currentTarget.dataset.selindex)
    let data = e.currentTarget.dataset.seldata
    this.setData({
      selItemIndex: index,
    })
    this.total_fee = data.jin_e
    this.msg_count = data.msgCount
  },

  
  payAction: function (e) {
  
    tt.showLoading({
      mask: true
    })
    var that = this;
    console.log("uid = " + that.cuid + "; token = " + that.token);
    var privatekey = utilMd5.hexMD5(that.cuid + "ttPay" + that.token);
    let subjectStr = " 美甲知识咨询"
    if (that.data.selItemIndex == 1) {
      subjectStr = " 美甲服务1次"
    } else if (that.data.selItemIndex == 2) {
      subjectStr = " 美甲服务10次"
    }
    var data = {
      "ac": "ttPay",
      "subject": that.uname + subjectStr,
      "uid": that.cuid,
      "openid": that.openid,
      "privatekey": privatekey,
      "total_fee": that.total_fee,
      "addnum": that.msg_count,
      // "total_fee": 0.01,//调试
      // "addnum": 1 //调试 添加信息的条数
    };
    console.log("充值请求参数：", data);
    
    //下单请求
    util.api_go({
      data: data,
      method: 'POST',
      success: function (responseData) {
        console.log("充值订单返回：", responseData);
        tt.hideLoading()
        var data = responseData.data;
        if (data) {
          //挂起微信支付请求
          var orderData = data.data;
          console.log(3333, orderData);
          tt.pay({
              orderInfo: {
                order_id: orderData.order_id,
                order_token: orderData.order_token
              },
              service: 5,
              success(res) {
                console.log("支付结果：", res)
                if (res.code == 0) {
                  // 支付成功处理逻辑，只有res.code=0时，才表示支付成功
                  // 但是最终状态要以商户后端结果为准
                  tt.showToast({
                    title: '充值成功',
                  })
                  that.getLoginUserInfo(true)
                }
              },
              fail(res) {
                console.log("支付失败：", res)
                app.dialog('充值失败', 'loading');
              }
            });
        } else {
          app.dialog('充值失败', 'loading');
        }
      }
    });
  },

  getLoginUserInfo: function (reAuth) {
    var that = this;
    //读取登录用户信息
    app.LoginUserInfo(function (res) {
      console.log("登录用户信息：", res);
      if (res && res != -1) {
        that.cuid = res.uid
        that.token = res.token
        that.openid = res.openid
        that.uname = res.uname
        that.hasScore = parseInt(res.invitesource)
        that.setData({
          hasMsgCount: parseInt(res.scorecoin) - parseInt(res.scorenum)
        });
        that.getPayRecord(that.cuid)
      }
    }, reAuth);
  },

  formatTimeStamp: function(timeStamp, day_join, time_join) {
    var date = new Date(timeStamp*1000)
    var year = date.getFullYear() - 2000
    var month = date.getMonth() + 1
    var day = date.getDate()
  
    var hour = date.getHours()
    var minute = date.getMinutes()
    var second = date.getSeconds()

    let timeStr = year + day_join + month + day_join + day + ' ' + hour + time_join + minute + time_join + second
    return timeStr
  },

  //获取充值记录
  getPayRecord (uid) {
    var that = this
    util.api_go({
      data:{
        ac: "getpayrecord",
        publickey: util.publickey,
        uid: uid
      },
      success: function (response) {
        console.log("充值记录：", response);
        if (!response.data.msg) {
          // 返回：time-充值时间、 coin-充值金额（元）、num-信息条数、result-充值结果（-1： 失败 1：成功）
          let recordArr = []
          let i = 1
          response.data.forEach(function (m) {
            let recordObj = {}
            let timeStr = that.formatTimeStamp(parseInt(m.time), '-', ':')
            let coinNum = parseInt(m.coin)
            let coin = ''
            if (coinNum >= 100) {
              coin = coinNum / 100
            } else {
              coin = (parseInt(m.coin) / 100).toFixed(2)
            }
            let record = i + '. ' + timeStr + " " + coin + "元 " + m.num + "条"
            i++
            recordObj.result = m.status
            let refundStatus = 0
            if(m.status == 1) {
              refundStatus = m.refund_status ? (m.refund_status == 1 ? 3 : 1) : 1
            }
            recordObj.status = refundStatus
            recordObj.refund_id = m.refund_id
            recordObj.str = record
            recordObj.coin = parseInt(m.coin)
            recordObj.num = m.num
            recordObj.out_trade_no = m.out_trade_no
            recordArr.push(recordObj)

          })
          that.buyRecords = recordArr
          that.setData({
            czRecord: recordArr
          })
        }
      }
    })
  },

  //获取兑换记录
  getDuihuanRecord (uid) {
    var that = this
    util.api_go({
      data:{
        ac: "douyinRecordList",
        publickey: util.publickey,
        uid: uid
      },
      success: function (response) {
        console.log("兑换记录：", response);
        if (!response.data.msg) {
          // 返回：time-充值时间、 coin-充值金额（元）、num-信息条数、result-充值结果（-1： 失败 1：成功）
          let recordArr = []
          let i = 1
          response.data.forEach(function (m) {
            let recordObj = {}
            recordObj.str = m.created_at + " 兑换" + m.title + "扣除" + m.score + "积分"
            recordArr.push(recordObj)
          })
          that.duihuanRecords = recordArr
          that.setData({
            czRecord: recordArr
          })
        }
      }
    })
  },

  goAtherPage: function (e) {
    console.log("goAtherPage!!!!!!!!");
    var url = e.currentTarget.dataset.link;
    tt.navigateTo({
      url: url
    })
  },

  getCanDuihuan: function() {
    // get请求 https://admin.jawanology.com/go.php?ac=getDuihuan&publickey=ZGZvI1mi8Q&id=1
    var that = this
    util.api_go({
      data:{
        ac: "getDuihuan",
        publickey: util.publickey,
        id: '1'
      },
      success: function (response) {
        console.log("可兑换服务：", response);
        if (!response.data.msg) {
          that.setData({
            duihuanDatas: response.data
          })
        }
      }
    })
  },

  duihuanAction(e) {
    var that = this
    var serviceData = e.currentTarget.dataset.service
    console.log("兑换：", serviceData)
    let needScore = parseInt(serviceData.score)
    if (this.hasScore >= needScore) {
      let contentStr = "扣除 " + serviceData.score + " 积分兑换：" + serviceData.title 
      tt.showModal({
        title: '提示',
        content: contentStr,
        confirmText: '确定',
        complete: (res) => {
          if (res.confirm) {
            that.duihuanRequest(serviceData.id, serviceData.image)
          }
        }
      });
    } else {
      tt.showToast({
        title: "积分不足"        
      });
    }
    
  },

  duihuanRequest(typeId, imageUrl) {
    // 生成兑换券、 post请求 go.php ac=douyinCardCreate 
    // 传入 type_id-上面列表兑换服务的id为要生成的兑换券类型 
    // uid-用户id 扣除相应积分数，返回card_no-兑换券码
    tt.showLoading({
      mask: true
    })
    var privatekey = utilMd5.hexMD5(this.cuid + "douyinCardCreate" + this.token);
    var data = {
      "ac": "douyinCardCreate",
      "uid": this.cuid,
      "type_id": typeId,
      "privatekey": privatekey,
    }
    var that = this
    console.log("兑换请求参数：", data)
    util.api_go({
      data: data,
      method: 'POST',
      success: function (responseData) {
        console.log("兑换返回：", responseData);
        tt.hideLoading()
        if(responseData.data.res){
          //这里去显示兑换券图片
          that.setData({
            quanImageUrl: imageUrl,
            showQuan: true
          })
          console.log("券图片链接：", that.data.quanImageUrl)
        } else {
          tt.showToast({
            title: responseData.data.msg
          });
        }
      }
    });
  },

  closeQuanView() {
    this.setData({
      showQuan: false
    })
  },

  selectedJilu(e) {
    var selectedTab = parseInt(e.currentTarget.dataset.index)
    this.setData({
      selected: selectedTab
    })
    if (selectedTab == 1) {
      if(this.buyRecords && this.buyRecords.length > 0) {
        this.setData({
          czRecord: this.buyRecords
        })
      } else {
        this.getPayRecord(this.cuid)
      }
    } else {
      if(this.duihuanRecords && this.duihuanRecords.length > 0) {
        this.setData({
          czRecord: this.duihuanRecords
        })
      } else {
        this.getDuihuanRecord(this.cuid)
      }
    }
  },

  tuikuanAction(e) {
      var that = this
      var chongzhiData = e.currentTarget.dataset.item
      console.log("退款：", chongzhiData)
      let msgCount = parseInt(chongzhiData.num)
      let coin = parseInt(chongzhiData.coin) / 100.0
      let orderNo = chongzhiData.out_trade_no
      console.log("hasMsgCount = " + this.data.hasMsgCount + ", msgCount = " + msgCount)
      if (this.data.hasMsgCount >= msgCount) {
        let contentStr = "退款将减少" + msgCount + "条可用信息数" 
        tt.showModal({
          title: '提示',
          content: contentStr,
          confirmText: '确定',
          complete: (res) => {
            if (res.confirm) {
              that.tuikuanRequest(orderNo, coin, msgCount)
            }
          }
        });
      } else {
        tt.showToast({
          title: "信息条数不足"        
        });
      }  
  },

  tuikuanRequest(orderId, coin, msgCount) {
    //     go.php
    // post请求
    // ac=out_order_no
    // {
    //  uid,用户id
    //  order_id,要退款的订单out_trade_no
    //  binduid,机构id
    //  addnum,消息减少的条数
    //  total_fee,退款金额（元）
    //  reason,退款原因
    //  subject,描述（选填）
    // }
    tt.showLoading({
      mask: true
    })
    var privatekey = utilMd5.hexMD5(this.cuid + "ttRefund" + this.token);
    var data = {
      "ac": "ttRefund",
      "uid": this.cuid,
      "order_id": orderId,
      "addnum": msgCount,
      "total_fee": coin,
      "reason": "申请退款",
      "subject": "",
      "privatekey": privatekey,
    }
    var that = this
    console.log("退款请求参数：", data)
    util.api_go({
      data: data,
      method: 'POST',
      success: function (responseData) {
        console.log("退款返回：", responseData);
        tt.hideLoading()
        if (responseData.data.res) {
          tt.showToast({
            title: "退款成功"
          });
        } else {
          tt.showToast({
            title: responseData.data.msg
          });
        }
      }
    });

  },

  // bind:refund 使用示例 
  handleRefund(event) {
    const { status, result } = event.detail;
    if (status === 'success') {
      console.log("退款操作成功：", result)
      const { refundId, outRefundNo } = result;

    } else {
      console.log("退款操作错误：", result)
    }
  },


  refundError(err) {
    console.log("退款错误信息：", err)
  }

})